<template>
  <div class="setSafety">
    <ul class="kuang">
      <li>
        <div>
          <div>
            <p>账户密码</p>
            <span
              >当前密码强度：
              <span :class="strength">{{ pwdIntensity }}</span>
            </span>
          </div>
          <span class="operation" @click="modification">修改</span>
        </div>
      </li>
      <li>
        <div>
          <div>
            <p>手机绑定</p>
            <span>已绑定手机：{{ cellPhone }}</span>
          </div>
          <span class="operation" @click="makePhone">修改</span>
        </div>
      </li>
      <li>
        <div>
          <div>
            <p>密保问题</p>
            <span v-if="questionState=='1'">已设置密保问题，密保问题可有效保护账户安全</span>
            <span>未设置密保问题，密保问题可有效保护账户安全</span>
          </div>
          <span class="operation" @click="openEncryptedClose">设置</span>
        </div>
      </li>
      <li>
        <div>
          <div>
            <p>备用邮箱</p>
            <span v-if="mailStatus === '1'">已绑定邮箱：xxxx@xxxx.com</span>
            <span v-else>未绑定邮箱请点击设置</span>
          </div>
          <span class="operation" v-if="mailStatus === '1'" @click="mailShow">修改</span>
          <span class="operation" v-else @click="mailShow">设置</span>
        </div>
      </li>
      <li>
        <div>
          <div>
            <p>注销账号</p>
            <span>如果您不再使用此账号，可以将其注销。账号成功注销后，其下所有服务、数据及隐私信息将会被删除并将无法恢复</span>
          </div>
          <span class="operation" @click="logout">注销</span>
        </div>
      </li>
    </ul>
    <el-dialog title="修改密码" :visible.sync="isconsult" width="30%" :before-close="consultClose">
      <el-form class="user-account-key" ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input type="password" placeholder="请输入原密码" v-model="form.oldPassword"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input type="password" placeholder="请设置新密码" v-model="form.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="affirmPassword">
          <el-input type="password" placeholder="请确认新密码" v-model="form.affirmPassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">保存</el-button>
          <el-button @click="$refs['form'].resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="设置密保问题" :visible.sync="isencrypted" width="30%" :before-close="encryptedClose">
      <el-select v-model="select" placeholder="请选择" style="width: 100%;margin-bottom: 15px;">
        <el-option v-for="(item, i) in encryptedData" :key="i" :label="item.desc" :value="item.type"> </el-option>
      </el-select>
      <el-input type="text" placeholder="请输入密保答案" v-model="input" style="margin-bottom: 15px;"></el-input>
      <el-button type="primary" @click="setEncrypted">提交</el-button>
    </el-dialog>
    <el-dialog title="修改手机号" :visible.sync="ModifyPhoneNumber" width="30%" :before-close="closePhone">
      <el-form class="user-account-key" ref="phoneRef" :model="phoneForm" :rules="rules" label-width="100px" style="width:100%">
        <el-form-item label="请输入要绑定的手机号" prop="phone" label-width="170px" >
          <el-input type="text" placeholder="请输入要绑定的手机号" v-model="phoneForm.phone" style=" width: 7l0%;"></el-input>
        </el-form-item>
        <el-form-item label="请输入验证码" prop="code" label-width="170px">
          <el-input type="text" style=" width: 50%;  margin-right: 20px;" placeholder="请输入验证码" v-model="phoneForm.code"></el-input>
          <el-button @click="getCode">{{ count }}</el-button>
        </el-form-item>
          <el-form-item >
          <el-button type="primary" @click="confirmPhone">保存</el-button>
          <el-button @click="$refs['phoneRef'].resetFields()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="修改邮箱" :visible.sync="mailshow" width="40%" :before-close="closeMail">
      <el-form class="user-account-key" ref="mailRef" :model="mailForm" :rules="rules" label-width="100px">
        <el-form-item label="请输入要绑定的邮箱" label-width="200px" prop="mail" style="width:80%">
          <el-input type="text" placeholder="请输入要绑定的邮箱" v-model="mailForm.mail"></el-input>
        </el-form-item>
        <el-form-item style="margin-left:0">
          <el-button type="primary" @click="issuccess">保存</el-button>
          <el-button @click="closeMail">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getItem,removeStore,setItem } from '@/utils/store.js'
import CryptoJS from '@/utils/CryptoJS'
import { sedCode, ModifyThePhoneNumber, sendmail, securityQuestion, securitySettings,cancelled,changePassword,updateUserinfo } from '@/views/userHome/api/setSafety.js'
export default {
  data() {
    //此处即表单发送之前验证
    let validateNewPassword = (rule, value, callback) => {
      if (value === this.form.oldPassword) {
        callback(new Error('新密码不能与原密码相同!'))
      } else {
        callback()
      }
    }
    let validateNewPassword2 = (rule, value, callback) => {
      if (value !== this.form.newPassword) {
        callback(new Error('与新密码不一致!'))
      } else {
        callback()
      }
    }
    var checkEmail = (rule, value, callback) => {
    const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (!value) {
      return callback(new Error('邮箱不能为空'))
    }
    setTimeout(() => {
      if (mailReg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的邮箱格式'))
      }
    }, 100)
  }
    return {
      input: '',
      select: '',
      pwdIntensity: '', //当前密码强度
      strength: '', //密码强度的class
      cellPhone: '', //当前绑定的手机号
      isconsult: false, //更改密码
      ModifyPhoneNumber: false, //更改手机号
      mailshow: false,
      isencrypted: false,
      mailStatus: '',
      questionState:'',
      form: {},
      encryptedData: [],
      mailForm: {},
      count: '发送验证码',
      phoneForm: {},
      rules: {
        oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '请设置新密码', trigger: 'blur' },
          { validator: validateNewPassword, trigger: 'blur' }
        ],
        affirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateNewPassword2, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error('请输入正确的手机号'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
        mail:[{ required: true, validator: checkEmail, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUser()
  },
  methods: {
    async updateUserinfo(){
        try {
        const data = await updateUserinfo()
        this.userdata = data.data
        setItem('USER_INFO', data)
        // console.log(data, '登录用户信息存储')
      } catch (error) {
        // console.log(error)
        this.$message.error(error)
      }
    },
    getUser() {
      //获取用户信息
      this.pwdIntensity = getItem('USER_INFO').data.data.pwdIntensity
      this.cellPhone = getItem('USER_INFO').data.data.phone
      this.mailStatus = getItem('USER_INFO').data.data.mailState
      this.questionState=getItem('USER_INFO').data.data.questionState
      if (this.pwdIntensity == '强') {
        this.strength = 'strong'
      }
      if (this.pwdIntensity == '良好') {
        this.strength = 'fine'
      }
      if (this.pwdIntensity == '弱') {
        this.strength = 'weak'
      }
    },
    consultClose() {
      // 关闭修改密码弹窗
      this.isconsult = false
      this.form = {}
    },
    async openEncryptedClose() {
      //打开设置密保问题弹窗
      this.isencrypted = true
      const { data: res } = await securityQuestion()
      // console.log(res)
      if (res.code == 0) {
        this.encryptedData = res.data
      } else {
        this.$message({
          type: 'warning',
          message: '获取密保问题失败'
        })
      }
    },
    async setEncrypted() {
      let userId = getItem('XIE_XIN').user_id
      let securityQuestion = this.select
      let securityAnswer = this.input
      let data = {
        userId,
        securityQuestion,
        securityAnswer
      }
      const { data: res } = await securitySettings(data)
      if (res.code === 0) {
        this.select = ''
        this.input = ''
        this.$message({
          type: 'success',
          message: '密保设置成功'
        })
        this.isencrypted = false
        this.updateUserinfo()
        this.getUser()
      } else {
        this.$message({
          type: 'warning',
          message: res.msg
        })
      }
    },
    encryptedClose() {
      //关闭设置密保问题弹窗
      this.isencrypted = false
    },
    makePhone() {
      //显示修改手机号的弹窗
      this.ModifyPhoneNumber = true
    },
    async getCode() {
      this.getCodeAction()
      let phone = this.phoneForm.phone
      const { data: res } = await sedCode(phone)
      if (res.code === 0) {
        this.$message.success('发送验证码成功')
      } else {
        this.$message.error(res.msg)
      }
    },
    // 验证码倒计时
    getCodeAction() {
      this.codeDisable = true
      const time = 60
      if (!this.timer) {
        this.count = time
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= time) {
            this.count--
          } else {
            this.show = true
            clearInterval(this.timer)
            this.timer = null
            this.codeDisable = false
            this.count = '重新获取验证码'
          }
        }, 1000)
      }
    },
    confirmPhone() {
      //提交修该手机号
      this.$refs.phoneRef.validate(async valid => {
        if (valid) {
          let userId = getItem('XIE_XIN').user_id
          let phone = this.phoneForm.phone
          let code = this.phoneForm.code
          let params = {
            userId: userId,
            phone: phone,
            code: code
          }
          const { data: res } = await ModifyThePhoneNumber(params)
          // console.log(res)
          if(res.code==0){
            this.ModifyPhoneNumber = false
            this.updateUserinfo()
            this.getUser()
          }
        } else {
          this.$message.error('请正确填写表单')
          return false
        }
      })
    },
    closePhone() {
      //关闭修改手机号码弹窗
      this.ModifyPhoneNumber = false
      this.phoneForm = {}
    },
    modification() {
      // 打开修改密码弹窗
      this.isconsult = true
    },
    onSubmit(formName) {
      // 确认修改密码
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          let userId = getItem('XIE_XIN').user_id
          let data = {
            oldPassword:CryptoJS.encrypt(this.form.oldPassword),
            newPassword:CryptoJS.encrypt(this.form.newPassword),
            affirmPassword:CryptoJS.encrypt(this.form.affirmPassword),
            userId
          }
          const {data:res} = await changePassword(data)
          if(res.code==0){
            this.$message.success('修改密码成功')
            this.form={}
            this.isconsult = false
            this.updateUserinfo()
            this.getUser()
          }
          // console.log(res);
          // console.log('修改密码成功')
        } else {
          this.$message.error('请正确填写表单')
          return false
        }
      })
    },
    logout() {
      //注销账号
      this.$confirm('账号成功注销后，其下所有服务、数据及隐私信息将会被删除并将无法恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          let userId = getItem('XIE_XIN').user_id
          let data={
            userId
          }
          const {data:res} =await cancelled(data)
          // console.log(res);
          if(res.code==0){
            removeStore({
            name: 'logininfo'
        })
            this.$store.commit('Setuser',null)
            this.$router.push({ path: '/login' })
            window.localStorage.clear()
            this.$message({
              type: 'success',
              message: '注销成功!'
            })
          }
          
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消注销'
          })
        })
    },
    mailShow() {
      this.mailshow = true
    },
    async issuccess() {
       this.$refs.mailRef.validate(async(valid) => {
         if(valid){
            let userId = getItem('XIE_XIN').user_id
            let mail = this.mailForm.mail
            let data = {
              userId,
              mail
            }
            const { data: res } = await sendmail(data)
            // console.log(res)
            if (res.code == 0) {
              this.$message({
                type: 'success',
                offset: 200,
                message: '发送邮件成功，请前往邮箱确认'
              })
              // this.$message.success(res.data)
            this.mailshow = false
        // this.$router.push({ name: 'MailLoading', params: { data: this.mailForm } })
      }
         }
       })
      // let userId = getItem('XIE_XIN').user_id
      // this.mailForm.userId = userId
      // this.$router.push({ name: 'MailLoading', params: { data: this.mailForm } })
     
    },
    closeMail() {
      //关闭邮箱弹出框
      this.mailForm={}
      this.mailshow = false
    }
  }
}
</script>
<style lang="less" scoped>
.setSafety {
  margin: 40px;
  li {
    > div {
      display: flex;
      justify-content: space-between;
      width: 100%;
      font-size: 16px;
      color: #333;
      border-bottom: 1px solid #eee;
      padding-bottom: 30px;
      .operation {
        font-size: 16px;
        width: 70px;
        height: 35px;
        margin-top: 20px;
        color: rgb(24, 144, 255);
        border: 0;
        cursor: pointer;
      }
      div {
        p {
          margin-bottom: 20px;
        }
        span {
          font-size: 12px;
          color: #777;
          .strong {
            color: green;
          }
          .weak {
            color: red;
          }
          .fine {
            color: orange;
          }
        }
      }
    }
  }
}
</style>
